﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Microsoft.EntityFrameworkCore;
using SX.AuthServer.Data;
using SX.AuthServer.Models;
using SX.Core;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace SX.AuthServer
{
    public class CustomResourceOwnerPasswordValidtor : IResourceOwnerPasswordValidator
    {
        private readonly ApplicationDbContext _dbContext;
        public CustomResourceOwnerPasswordValidtor(ApplicationDbContext applicationDbContext)
        {
            _dbContext = applicationDbContext;
        }

        /// <summary>
        /// 验证登录信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user= _dbContext.Set<ApplicationUser>().Where(x => x.UserName == context.UserName).FirstOrDefault();
            if (user == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号输入有误!");
                return;
            }

            var password = Md5Encrypt.Encrypt32(context.Password);
            if (user.Password != password)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "密码输入有误!");
                return;
            }
            context.Result = new GrantValidationResult(user.Id, OidcConstants.AuthenticationMethods.Password);
        }

    }

}
